import React, { Component } from 'react';
import axios from 'axios';
import cookie from 'react-cookies';
import MenuHead from '../comm/menuHead';
import Table from '../comm/table';
import TableL from '../comm/table_l';
import {has} from '../comm/collection';
import {rsaEncode} from '../comm/rsa';

const userListTab = "userListTab";
const userDetailTab = "userDetailTab";
const editRoleTab = "editRoleTab";
const block = "block";
const none = "none";
const add_user = "add_user";
const alter_user = "alter_user";

class User extends Component {
  state = {
    cur_tab: userListTab,
    userHead: [{en: 'user_name', ch: '用户'},],
    userData: [],
    userList_count: 0,
    user_id: "",
    pub_key: "",
    user_name: "",
    user_pwd: "",
    user_role: [],
    all_role: [],
    roleHead: [{en: 'role', ch: '角色'},],
    roleListLeft: [],
    roleListRight: [],
    add_or_alter_user: "",
  }
  queryUserList = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/queryUser", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        userData: res.data.user_list,
        userList_count: res.data.user_list.length,
      })
    }).catch((err) => {
      alert(err)
    })
    axios.post("/app/queryRole", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        all_role: res.data.role,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  getUserPubKey = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/getUserPubKey", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        user_id: res.data.user_id,
        pub_key: res.data.pub_key,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  addUser = () => {
    this.getUserPubKey();
    this.setState({
      cur_tab: userDetailTab,
      add_or_alter_user: add_user,
    })
  }
  cancelAddUser = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/cancelAddUser", {
      "user_id": this.state.user_id,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
    }).catch((err) => {
      alert(err)
    })
  }
  cancelEditUser = () => {
    if(this.state.add_or_alter_user === add_user) {
      this.cancelAddUser()
    }
    this.setState({
      cur_tab: userListTab,
    })
    this.clearEdit();
  }
  clearEdit = () => {
    this.setState({
      user_id: "",
      pub_key: "",
      user_name: "",
      user_pwd: "",
      user_role: [],
      })
  }
  comfirmAddUser = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    let pwd = rsaEncode(this.state.user_pwd, this.state.pub_key);
    if(this.state.pub_key === "") {
      alert("pub_key为空");
      return;
    }
    if(this.state.user_id === "") {
      alert("user_id为空");
      return;
    }
    if(this.state.user_name === "") {
      alert("user_name为空");
      return;
    }
    if(this.state.user_pwd === "") {
      alert("user_pwd为空");
      return;
    }
    axios.post("/app/confirmAddUser", {
      "user_id": this.state.user_id,
      "user_name": this.state.user_name,
      "user_pwd": pwd,
      "user_role": this.state.user_role,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.queryUserList();
      this.clearEdit();
      this.setState({
        cur_tab: userListTab,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  queryUserRole = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/queryUserRole", {
      "user_name": this.state.user_name,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      let user_role = res.data.user_role;
      let left = [];
      let right = [];
      let all_role = this.state.all_role;
      for(let i = 0; i < all_role.length; i++){
        if(user_role.indexOf(all_role[i]["role"]) === -1) {
          left.push(all_role[i]);
        } else {
          right.push(all_role[i]);
        }
      }
      this.setState({
        roleListLeft: left,
        roleListRight: right,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  modifyUserList = (data) => {
    this.getUserPubKey();
    this.setState({
      add_or_alter_user: alter_user,
      user_name: data["user_name"],
      cur_tab: userDetailTab,
    })
  }
  set_user_name = (e) => {
    this.setState({
      user_name: e.target.value,
    })
  }
  set_user_pwd = (e) => {
    this.setState({
      user_pwd: e.target.value,
    })
  }
  editRole = () => {
    this.setState({
      cur_tab: editRoleTab,
    })
    if(this.state.add_or_alter_user === alter_user){
      this.queryUserRole();
      return;
    }
    this.setState({
      roleListLeft: this.state.all_role,
      roleListRight: [],
    })
  }
  cancelEditRole = () => {
    this.setState({
      cur_tab: userDetailTab,
    })
  }
  comfirmAddRole = () => {
    let right = this.state.roleListRight;
    let role_list = [];
    for(let i = 0; i < right.length; i++){
      role_list.push(right[i]["role"]);
    }
    this.setState({
      user_role: role_list,
      cur_tab: userDetailTab,
    })
  }
  shiftRight = (records) => {
    let left = [];
    let right = [...this.state.roleListRight];
    let roleList = [...this.state.roleListLeft];
    for(let i = 0; i < roleList.length; i++){
      roleList[i].checked = false;
      if(records.indexOf(roleList[i]["id"]) === -1) {
        if(!has(left, roleList[i], "id")) {
          left.push(roleList[i]);
        }
      } else {
        if(!has(right, roleList[i], "id")) {
          right.push(roleList[i]);
        }
      }
    }
    this.setState({
      roleListLeft: left,
      roleListRight: right,
    })
  }
  shiftLeft = (records) => {
    let left = [...this.state.roleListLeft];
    let right = [];
    let roleList = [...this.state.roleListRight];
    for(let i = 0; i < roleList.length; i++){
      roleList[i].checked = false;
      if(records.indexOf(roleList[i]["id"]) === -1) {
        if(!has(right, roleList[i], "id")) {
          right.push(roleList[i]);
        }
      } else {
        if(!has(left, roleList[i], "id")) {
          left.push(roleList[i]);
        }
      }
    }
    this.setState({
      roleListLeft: left,
      roleListRight: right,
    })
  }
  batchDelUserList = (records) => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    let userData = this.state.userData;
    let user_list = [];
    for(let i = 0; i < userData.length; i++) {
      if(records.indexOf(userData[i]["id"]) !== -1) {
        user_list.push(userData[i]["user_name"]);
      }
    }
    axios.post("/app/delUser", {
      "user_name": user_list,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.queryUserList();
    }).catch((err) => {
      alert(err)
    })
  }
  render() {
    let isUserListShow = this.state.cur_tab === userListTab ? block : none;
    let isUserDetailShow = this.state.cur_tab === userDetailTab ? block : none;
    let isEditRoleTab = this.state.cur_tab === editRoleTab ? block : none;
    return (
      <div align='center'>
        <MenuHead />
        <div style={{display: `${isUserListShow}`}}>
          <button onClick={this.addUser}>新增用户</button>
          <Table
            head={this.state.userHead}
            data={this.state.userData}
            queryData={this.queryUserList}
            deleteData={this.batchDelUserList}
            modifyData={this.modifyUserList}
            recordCount={this.state.userList_count} />
        </div>
        <div style={{display: `${isUserDetailShow}`}}>
          <table>
          <tbody>
          <tr>
          <td><button onClick={this.cancelEditUser}>取消</button></td>
          <td width='20'></td>
          <td><button onClick={this.comfirmAddUser}>确定</button></td>
          </tr>
          </tbody>
          </table>
          <table>
          <tbody>
          <tr>
            <td>用户名：</td>
            <td><input type='text' size='20' onChange={this.set_user_name}
                  value={this.state.user_name}/></td>
          </tr>
          <tr>
            <td>密码：</td>
            <td><input type='text' size='20' onChange={this.set_user_pwd}
                  value={this.state.user_pwd}/></td>
          </tr>
          <tr>
            <td>角色：</td>
            <td><button onClick={this.editRole}>编辑角色</button></td>
          </tr>
          </tbody>
          </table>
        </div>
        <div style={{display: `${isEditRoleTab}`}}>
          <table>
          <tbody>
          <tr>
          <td><button onClick={this.cancelEditRole}>取消</button></td>
          <td width='20'></td>
          <td><button onClick={this.comfirmAddRole}>确定</button></td>
          </tr>
          </tbody>
          </table>
          <table>
          <tbody>
          <tr>
            <td>
            <TableL 
              head={this.state.roleHead}
              data={this.state.roleListLeft}
              filter={["role"]}
              deleteName={"右移"}
              deleteData={this.shiftRight}/>
            </td>
            <td>
            <TableL 
              head={this.state.roleHead}
              data={this.state.roleListRight}
              filter={["role"]}
              deleteName={"左移"}
              deleteData={this.shiftLeft}/>
            </td>
          </tr>
          </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default User;
